<?php
class Pageley_Gateway_Database_Condition_MultipleSqlDecorator extends Pageley_Gateway_Database_Condition_AbstractSqlDecorator {

    private $query;

    public function __construct($decoratedCondition, $query) {
        parent::__construct($decoratedCondition);
        $this->query = $query;
    }

    protected function createSql() {
        return $this->getColumnExpression() .
            " " . $this->getOperator() .
            " " . $this->getDecoratedCondition()->getKeyExpression();
    }
    
    public function getColumnExpression() {
        $attribute = $this->getAttribute();
        $type = $this->getType();
        $joinedTable = $this->getQuery()->getTable($attribute->getType());
        $joinedGenerator = $joinedTable->getColumnNameGenerator();
        return $this->getQuery()->getAlias($type) .
            ".\"" . $joinedGenerator->getIdColumnName() . "\"";
    }
    
    public function getFromClause() {
        $type = $this->getType();
        $alias = $this->getQuery()->getAlias($this->getQuery()->getType());
        $joinedTable = $this->getQuery()->getTable($type);
        $propertyName = $this->getDecoratedCondition()->getPropertyName();
        $joinedAlias = $this->getQuery()->getAlias($type);
        $columnName = $this->getQuery()->getColumnName("id");
        return " INNER JOIN " . $joinedTable->getFullTableName() . " AS " . $joinedAlias 
            . " ON " . $alias . ".\"" . $columnName . "\" = "
            . $joinedAlias . ".\"" . $columnName . "\"";
    }
    
    private function getType() {
        $attribute = $this->getAttribute();
        $type = null;
        if($attribute->isManyToMany()) {
            $type = $attribute->getRelationType($this->getQuery()->getType());
        } else {
            $type = $attribute->getType();
        }
        return $type;
    }
    
    public function getValues() {
        $values = $this->getDecoratedCondition()->getValues();
        $sqlValues = new Pageley_Util_ArrayMap();
        foreach($values as $key => $value) {
            $sqlKey = Pageley_Util_String::addUnderscores(Pageley_Util_String::replace($key, ".", "_"));
            $sqlValues->put($sqlKey, $value->getId());
        }
        return $sqlValues;
    }
    
    protected function getAttribute() {
        $type = $this->getQuery()->getType();
        $propertyName = $this->getDecoratedCondition()->getPropertyName();
        $attribute = $type->getAttribute($propertyName);
        if($attribute === null) {
            throw new Pageley_Gateway_Database_Exception("No such property '" . $propertyName . "' on type '" . $type->getFullName() . "'.");
        }
        return $attribute;
    }

    public function getQuery() {
        return $this->query;
    }
}